package top.guxx.mall.service.impl;

import org.springframework.stereotype.Service;
import retrofit2.Call;
import top.guxx.mall.config.RedisService;
import top.guxx.mall.domain.req.WeChatQrCodeReq;
import top.guxx.mall.domain.res.WeChatQrCodeRes;
import top.guxx.mall.domain.res.WeChatTokenRes;
import top.guxx.mall.domain.vo.WeChatTemplateMessageVO;
import top.guxx.mall.service.ILoginService;
import top.guxx.mall.service.IWeChatApiService;

import org.springframework.beans.factory.annotation.Value;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author：Guxx
 * @Description：
 * @Date：2024/11/2 20:46
 * @Filename：LoginServiceImpl
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Value("${wechat.config.app-id}")
    private String appId;

    @Value("${wechat.config.app-secret}")
    private String appSecret;

    @Value("${wechat.config.template_id}")
    private String template_id;

    @Resource
    private RedisService redisService;
    @Resource
    private IWeChatApiService weChatApiService;

    @Override
    public String createQrCodeTicket() throws Exception {
        String accessToken = redisService.get(appId);
        if (accessToken == null){
            accessToken = createAccessToken();
        }
        // 2. 生成 ticket
        WeChatQrCodeReq weChatQrCodeReq = WeChatQrCodeReq.builder()
                .expire_seconds(2592000)
                .action_name(WeChatQrCodeReq.ActionNameTypeVO.QR_SCENE.getCode())
                .action_info(WeChatQrCodeReq.ActionInfo.builder()
                        .scene(WeChatQrCodeReq.ActionInfo.Scene.builder()
                                .scene_id(123)
                                .build())
                        .build())
                .build();
        Call<WeChatQrCodeRes> qrCodeResCall = weChatApiService.createQRCode(accessToken, weChatQrCodeReq);
        WeChatQrCodeRes weChatQrCodeRes = qrCodeResCall.execute().body();
        assert weChatQrCodeRes != null;
        return weChatQrCodeRes.getTicket();
    }

    @Override
    public String checkLogin(String ticket) {
        return redisService.get(ticket);
    }

    @Override
    public void saveLoginState(String ticket, String openid) throws Exception {
        String accessToken = redisService.get(appId);
        if(accessToken == null){
            accessToken = createAccessToken();
        }

        redisService.set(ticket, openid, 60 * 60 * 2L);

        // 2. 发送模板消息
        Map<String, Map<String, String>> data = new HashMap<>();
        WeChatTemplateMessageVO.put(data, WeChatTemplateMessageVO.TemplateKey.USER, openid);

        WeChatTemplateMessageVO templateMessageDTO = new WeChatTemplateMessageVO(openid, template_id);
        templateMessageDTO.setUrl("http://guxx.top");
        templateMessageDTO.setData(data);

        Call<Void> call = weChatApiService.sendMessage(accessToken, templateMessageDTO);
        call.execute();

    }

    private String createAccessToken() throws Exception{
        String accessToken = null;
        Call<WeChatTokenRes> call = weChatApiService.getToken("client_credential", appId, appSecret);
        WeChatTokenRes weChatTokenRes = call.execute().body();
        assert weChatTokenRes != null;
        accessToken = weChatTokenRes.getAccess_token();
        //设置微信凭证有效期为30分钟，
        //Long expire = 2592000L;
        Long expire = 60 * 60 * 2L;
        redisService.set(appId,accessToken,expire);
        return accessToken;
    }
}
